//
//  FirstViewController.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/15.
//

import UIKit
import MJRefresh

class LYOrderViewController: LYBaseViewController {
    
    private let orderListView = LYOrderListView()
    private let topView = LYOrderTopView()
    
    private let radioButtonGroup = LYRadioButtonGroupView()
    var orderListSelect: OrderListSelect = .all
    var selectIndex = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.bgImage = nil
        self.title = LYlocalizedString("Order")
        self.isHiddenCustomTabBar = false
        self.view.backgroundColor = UIColor(hex: "#FC7900")

        commonInitSubviews()
        fetchData()
    }
    
    // 刷新列表
    func updateData(tab: String) {
        switch tab {
        case "1":
            self.orderListSelect = .all
            selectIndex = 0
        case "2":
            self.orderListSelect = .progress
            selectIndex = 1
        case "3":
            self.orderListSelect = .pendingRepayment
            selectIndex = 2
        case "4":
            self.orderListSelect = .settled
            selectIndex = 3
        default:
            break
        }
        
        radioButtonGroup.selectButton(at: selectIndex)
        
        LYHUDUtils.showLoading()
        orderListView.tableView.mj_header?.beginRefreshing()
    }
    
    func commonInitSubviews() {
        self.view.addSubview(topView)

        let titles = [LYlocalizedString("All"),
                      LYlocalizedString("Applying"),
                      LYlocalizedString("Repayment"),
                      LYlocalizedString("Finish")]
        
        let normalImages = ["order_all",
                            "order_applying",
                            "order_repayment",
                            "order_finish"]
        radioButtonGroup.setDatas(titles: titles,
                                  normalImages: normalImages,
                                  selectedImages: normalImages)
        var seletedIndex = 0
        switch self.orderListSelect {
        case .all:
            seletedIndex = 0
        case .progress:
            seletedIndex = 1
        case .pendingRepayment:
            seletedIndex = 2
        case .settled:
            seletedIndex = 3
        }
        
        radioButtonGroup.selectButton(at: seletedIndex)
        
        radioButtonGroup.delegate = self
        
        view.addSubview(radioButtonGroup)
        orderListView.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let self = self else { return }
            self.fetchData()
        })
        
        if let header = orderListView.tableView.mj_header as? MJRefreshNormalHeader {
            header.setTitle("", for: .idle)
            header.setTitle("", for: .pulling)
            header.setTitle("", for: .refreshing)
            header.lastUpdatedTimeLabel?.isHidden = true
            header.stateLabel?.isHidden = true
        }
        
        orderListView.didClickCellClourse = { [weak self] sep in
            guard let self = self,
                  let url = sep.cracyfier else { return }
            if url.hasPrefix("http") || url.hasPrefix("https") {
                self.pushToWebViewController(url)
            } else {
                LYSchemeManager.shared.parser(url)
            }
        }
        self.view.addSubview(orderListView)
        
        let aspectRatio = 91.0 / 346.0
        let margin = 15.0
        let height = (SCREEN_WIDTH - margin * 2) * aspectRatio
        topView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.leading.trailing.equalToSuperview().inset(margin)
            make.height.equalTo(height)
        }
        
        radioButtonGroup.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom).offset(5)
            make.leading.trailing.equalTo(topView)
            make.height.equalTo(40)
        }
        
        orderListView.snp.makeConstraints { make in
            make.top.equalTo(radioButtonGroup.snp.bottom).offset(5)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview().offset(-bottomMargin - customTabBarHeight)
        }
    }
    
    @objc func fetchData() {
//        LYHUDUtils.showLoading()
        self.lyCurrentState = .loading
        LYStocksManager.fetchOrderList(orderListSelect: self.orderListSelect) { [weak self] model, msg, error in
            guard let self = self else { return }
            if error == nil {
                self.orderListView.dataSources = model?.septenier ?? []
                self.lyCurrentState = self.orderListView.dataSources.isEmpty ? .noData : .finished
                LYHUDUtils.hideHUD()
            } else {
                self.lyCurrentState = .noNetwork
                LYHUDUtils.showToast(msg)
            }
            self.orderListView.tableView.mj_header?.endRefreshing()
            lyUpdateState(self.lyCurrentState)
        }
    }
    
    func pushToWebViewController(_ url: String) {
        let webviewVC = LYWebViewController()
        webviewVC.urlString = url
        UIApplication.topViewController()?.navigationController?.pushViewController(webviewVC, animated: true)
    }
}

extension LYOrderViewController: LYRadioButtonGroupViewDelegate {
    func radioButtonGroupView(_ view: LYRadioButtonGroupView, didSelectButtonAt index: Int) {
        let orderListSelects: [OrderListSelect] = [.all, .progress, .pendingRepayment, .settled]
        guard index < orderListSelects.count else { return }
        self.orderListSelect = orderListSelects[index]
        self.selectIndex = index
        LYHUDUtils.showLoading()
        fetchData()
    }
}

extension LYOrderViewController: LYStateDisplayable {
    var lyStateContainer: UIView {
        return self.orderListView.tableView
    }
    
    func lyFrame(for state: LYState) -> CGRect? {
        switch state {
        case .noData, .noNetwork:
            return CGRect(x: 0, y: 60, width: view.bounds.width, height: 300)
        default:
            return nil
        }
    }

    func lyImage(for state: LYState) -> UIImage? {
        switch state {
        case .noData:
            return UIImage(named: "no_data_icon")
        case .noNetwork:
            return UIImage(named: "no_network_icon")
        default:
            return nil
        }
    }
    
    func lyMessage(for state: LYState) -> String {
        return ""
    }
    
    func lyTitle(for state: LYState) -> String {
        switch state {
        case .noData:
            return LYlocalizedString("No orders at the moment")
        case .noNetwork:
            return LYlocalizedString("No network available at the moment")
        default:
            return ""
        }
    }
    
    func lyButtonTitle(for state: LYState) -> String? {
        switch state {
        case .noData:
            return LYlocalizedString("Apply")
        case .noNetwork:
            return LYlocalizedString("Try it")
        default:
            return ""
        }
    }
    
    func lyDidTapStateButton() {
        switch self.lyCurrentState {
        case .noData:
            if let mainVC = UIApplication.shared.currentKeyWindow?.rootViewController as? LYMainViewController {
                mainVC.changeViewController(to: 0)
            }
        case .noNetwork:
            fetchData()
        default:
            break
        }
    }
}
